package com.sys.platform.service.impl;

import cn.hutool.core.date.DateUtil;
import com.sun.jna.Pointer;
import com.sys.platform.common.utils.SfxGateSDK;
import com.sys.platform.common.utils.StringUtils;
import com.sys.platform.entity.EntranceGuard;
import com.sys.platform.entity.GateRequest;
import com.sys.platform.mapper.EntranceGuardMapper;
import com.sys.platform.service.BarrierGateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

@Slf4j
@Service
public class BarrierGateServiceImpl implements BarrierGateService {

    private static final String url = "http://10.36.1.235:10502/device/barrierGate/callback";

    @Autowired
    private EntranceGuardMapper entranceGuardMapper;

    private Map<String, Pointer> map = new HashMap<>(50);

    /**
     * 分配一个道闸实例
     *
     * @param gate
     * @return
     */
    public Pointer sfxAllocGate(GateRequest gate) {
        if (map.containsKey(gate.getIpAddress())) {
            map.get(gate.getIpAddress());
        }
        return null;
    }

    @PostConstruct
    public void initializationGate() {
        List<EntranceGuard> entranceGuardList = entranceGuardMapper.selectEntranceGuardList();
        for (EntranceGuard gate : entranceGuardList) {
            log.info("===========初始化连接开始=========" + gate);
            try {
                //分配一个道闸实例
                Pointer pointer = SfxGateSDK.ins.sfxAllocGate(1, gate.getIpAddress(), gate.getPort(), url);
                //使用containsKey判断键是否存在
                if (map.containsKey(gate.getIpAddress())) {
                    return;
                }
                log.info("道闸ip: {} 初始化连接成功", gate.getIpAddress());
                map.put(gate.getIpAddress(), pointer);
            } catch (Exception e) {
                continue;
            }
        }
        log.info("获取到所有pointer指针: {}", map);

    }

    /**
     * 断开连接并且释放
     *
     * @param pointer
     */
    public void freeGate(Pointer pointer, String ip) {
//        SfxGateSDK.ins.sfxDisconnectGate(pointer);
        SfxGateSDK.ins.sfxFreeGate(pointer);
        log.info("道闸ip：{}，断开连接并释放成功", ip);
    }


    @Override
    public void openBarrierGate(GateRequest gate) {
        Pointer pointer = sfxAllocGate(gate); //分配
        if (StringUtils.isNull(pointer)) {
            return;
        }
        //连接道闸
//        SfxGateSDK.ins.sfxConnectGate(pointer, gate.getIpAddress(), gate.getPort());
        //开闸
        SfxGateSDK.ins.sfxOpenGate(pointer);
        log.info("道闸ip: {} 开闸成功", gate.getIpAddress());
        //释放
        //freeGate(pointer, gate.getIpAddress());

        log.info("开闸成功参数：{}", gate);
    }

    @Override
    public void close(GateRequest gate) {
        Pointer pointer = sfxAllocGate(gate); //分配
        if (StringUtils.isNull(pointer)) {
            return;
        }
        //连接道闸
//        SfxGateSDK.ins.sfxConnectGate(pointer, gate.getIpAddress(), gate.getPort());
        //关闸
        SfxGateSDK.ins.sfxCloseGate(pointer);
        log.info("道闸ip: {} 关闸成功", gate.getIpAddress());
        //释放
        //freeGate(pointer, gate.getIpAddress());

        log.info("关闸成功参数：{}", gate);
    }


    @Override
    public List<Map<String, Object>> whiteList(GateRequest gate) {
        List<Map<String, Object>> list = new ArrayList<>();
        Pointer pointer = sfxAllocGate(gate); //分配
        if (StringUtils.isNull(pointer)) {
            return list;
        }
        //连接道闸
//        SfxGateSDK.ins.sfxConnectGate(pointer, gate.getIpAddress(), gate.getPort());
        log.info("ip:{}, pointer指针：{}", gate.getIpAddress(), pointer);

        Pointer gateWhilteList = SfxGateSDK.ins.sfxGetGateWhilteList(pointer);
        //获取数量
        int count = SfxGateSDK.ins.sfxGetGateWhilteCount(pointer);
        SfxGateSDK.SfxGatePlate sfxGatePlate = null;

        try {
            for (int i = 0; i < count; i++) {
                Map<String, Object> map = new HashMap<>();
                sfxGatePlate = new SfxGateSDK.SfxGatePlate(gateWhilteList.share(25 * i));
                String carNumber = new String(sfxGatePlate.plate, "GBK").replace("\u0000", "").replace("\\u0000", "");
//                log.info("白名单列表：{}, 车牌：{}", i, carNumber);
                String date = sfxGatePlate.expired.year + "-" + sfxGatePlate.expired.month + "-" + sfxGatePlate.expired.day;
                map.put("carNumber", carNumber);
                map.put("date", date);
                map.put("count", i + 1);
                list.add(map);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("白名单列表数量：{}, ip：{}", count, gate.getIpAddress());
        //释放
        //freeGate(pointer, gate.getIpAddress());
        return list;
    }


    @Override
    public void addWhiteList(GateRequest gate) {
        Pointer pointer = sfxAllocGate(gate); //分配
        if (StringUtils.isNull(pointer)) {
            return;
        }
        //连接道闸
//        SfxGateSDK.ins.sfxConnectGate(pointer, gate.getIpAddress(), gate.getPort());

        Date dateNow = DateUtil.date();
        int year = DateUtil.year(dateNow);
        int month = DateUtil.month(dateNow) + 1;
        int day = DateUtil.dayOfMonth(dateNow);

        SfxGateSDK.SfxDate date = new SfxGateSDK.SfxDate();
        date.year = year;
        date.month = (byte) month;
        date.day = (byte) day;
        SfxGateSDK.ins.sfxAddPlateGate(pointer, gate.getCarNumber(), date);
        log.info("数量: {} 新增成功", SfxGateSDK.ins.sfxGetGateWhilteCount(pointer));
        //释放
        //freeGate(pointer, gate.getIpAddress());
        log.info("添加白名单参数：{}", gate);
    }


    @Override
    public void delWhiteList(GateRequest gate) {
        Pointer pointer = sfxAllocGate(gate); //分配
        if (StringUtils.isNull(pointer)) {
            return;
        }
        //连接道闸
//        SfxGateSDK.ins.sfxConnectGate(pointer, gate.getIpAddress(), gate.getPort());

        int t = SfxGateSDK.ins.sfxDelPlateGate(pointer, gate.getCarNumber());
        log.info("=========" + t);
        //释放
        //freeGate(pointer, gate.getIpAddress());
        log.info("删除成功参数：{}", gate);
    }

    @Override
    public void enable(GateRequest gate) {
        //分配一个道闸实例
        Pointer pointer = SfxGateSDK.ins.sfxAllocGate(1, gate.getIpAddress(), gate.getPort(), url);
        log.info("道闸ip: {} 初始化连接成功", gate.getIpAddress());
        map.put(gate.getIpAddress(), pointer);
    }

    @Override
    public void disabled(GateRequest gate) {
        SfxGateSDK.ins.sfxFreeGate(map.get(gate.getIpAddress()));
        log.info("道闸ip：{}，断开连接并释放成功", gate.getIpAddress());
        map.remove(map.get(gate.getIpAddress()));
    }
}
